package com.yitao.cms.utils;

import org.apache.commons.lang.StringUtils;

/**
 * @Author: wwl
 * @Date: 2020/4/9 16:36
 * @Description:字符处理工具类
 */
public class StringDealUtils {
    /**
     * 处理特殊字符问题(微信或表格携带的不展示字符)
     *
     * @param phone
     * @return
     */
    public static String dealBlankString(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            phone = removeNonAscii(phone);
            phone = removeSomeControlChar(phone);
            phone = removeFullControlChar(phone).trim();
            return phone;
        }
        return null;
    }

    /**
     * 去除非ascii码字符
     *
     * @param str
     * @return
     */
    public static String removeNonAscii(String str) {
        return str.replaceAll("[^\\x00-\\x7F]", "");
    }

    /**
     * 去除不可打印字符
     *
     * @param str
     * @return
     */
    public static String removeNonPrintable(String str) {
        return str.replaceAll("[\\p{C}]", "");
    }

    /**
     * 去除一些控制字符 Control Char
     *
     * @param str
     * @return
     */
    public static String removeSomeControlChar(String str) {
        return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); // Some Control Char
    }

    /**
     * 去除一些换行制表符
     *
     * @param str
     * @return
     */
    public static String removeFullControlChar(String str) {
        return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
    }

    /**
     * 统计字符串中特定字符的出现次数
     * @param str
     * @param key
     * @return
     */
    public static int getCount(String str, String key) {
        if (str == null || key == null || "".equals(str.trim()) || "".equals(key.trim())) {
            return 0;
        }
        int count = 0;
        int index = 0;
        while ((index = str.indexOf(key, index)) != -1) {
            index = index + key.length();
            count++;
        }
        return count;
    }


    public static void main(String[] args) {
       /* String password1 = "16473328838\u202C";
        String password2 = "16473328838";
        System.out.println("password1:" + password1.length());
        System.out.println("password2:" + password2.length());
        System.out.println("password1:" + StringDealUtils.dealBlankString(password1).length());
        System.out.println("password2:" + StringDealUtils.dealBlankString(password2).length());*/
       System.out.println(StringDealUtils.getCount("？测试数据？","？"));
       String str = "？测试数据？\uD83C\uDD95";
        System.out.println(str.length());
    }
}
